<template>
  <div class="choose-point-page">
    <!-- 搜索模式 -->
    <div v-if="searchMode" class="search-mode">
      <div class="search-header">
        <button @click="cancelSearch">取消</button>
        <h2>{{ searchMode === 'start' ? '选择起点' : '选择终点' }}</h2>
      </div>

      <div class="search-input">
        <input
            v-model="keyword"
            placeholder="请输入搜索关键词..."
            class="search-box"
        />
      </div>

      <div class="search-results">
        <div
            v-for="item in filteredResults"
            :key="item.id"
            class="result-item"
            @click="selectPoint(item)"
        >
          <div class="result-title">{{ item.name }}</div>
          <div class="result-details">
            <span>{{ item.room_code }}</span>
            <span>|</span>
            <span>{{ item.floor }}F</span>
          </div>
        </div>

        <div v-if="filteredResults.length === 0 && keyword" class="no-results">
          暂无搜索结果
        </div>
      </div>
    </div>

    <!-- 正常模式 -->
    <div v-else class="normal-mode">
      <div class="header">
        <h1>行政中心室内虚拟导引</h1>
        <p>请选择起点和终点开始导航</p>
      </div>

      <div class="content">
        <div class="location-info">
          <div class="location-icon">
            <img :src="locationIcon" alt="当前位置"/>
          </div>
          <div class="location-text">
            <h2>当前位置</h2>
            <p>浙江师范大学-行政中心</p>
          </div>
        </div>

        <div class="selected-points">
          <div class="point-display">
            <h3>起点: {{ selectedStartPoint?.name || '未设置' }}</h3>
            <h3>终点: {{ selectedEndPoint?.name || '未设置' }}</h3>
          </div>
        </div>

        <div class="action-buttons">
          <button class="primary-button" @click="startSearchStartPoint">
            设置起点
          </button>
          <button class="secondary-button" @click="startSearchEndPoint">
            设置终点
          </button>
        </div>
      </div>

      <div class="footer">
        <button
            class="start-navigation"
            @click="startNavigation"
            :disabled="!selectedStartPoint || !selectedEndPoint"
        >
          开始导航
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import locationIcon from '/img/indoor.png'
import { search_point } from "@/api/mock/index.js"

export default {
  name: 'ChoosePoint',
  setup() {
    const router = useRouter()
    const searchMode = ref('') // 'start' 或 'end'，表示当前搜索模式
    const keyword = ref('')
    const allResults = ref([])
    const selectedStartPoint = ref(null)
    const selectedEndPoint = ref(null)
    const startPoint = ref(null)
    const endPoint = ref(null)

    const startSearchStartPoint = () => {
      searchMode.value = 'start'
      keyword.value = ''
      allResults.value = []
    }

    const startSearchEndPoint = () => {
      searchMode.value = 'end'
      keyword.value = ''
      allResults.value = []
    }

    const selectPoint = (item) => {
      if (searchMode.value === 'start') {
        selectedStartPoint.value = item
        startPoint.value = item
        localStorage.setItem('currentRoomDoorNum', item.id)
      } else if (searchMode.value === 'end') {
        selectedEndPoint.value = item
        endPoint.value = item
      }
      searchMode.value = '' // 退出搜索模式
    }

    const cancelSearch = () => {
      searchMode.value = ''
    }

    const startNavigation = () => {
      if (selectedStartPoint.value && selectedEndPoint.value) {
        router.push(`/?id=${startPoint.value.id}&targetId=${endPoint.value.id}&targetFloor=F${endPoint.value.floor}`)
      }
    }

    async function fetchResults(kw) {
      try {
        console.log('开始搜索:', kw)
        const response = await search_point(kw)
        console.log('原始响应数据:', response)
        
        // 打印后端返回的完整数据
        console.log('后端传送来的搜索结果:', response.data)
        
        if (Array.isArray(response.data)) {
          allResults.value = response.data
          console.log('搜索结果数组:', allResults.value)
        } else {
          console.warn('接口返回非数组数据:', response)
          allResults.value = []
        }
      } catch (error) {
        console.error('搜索失败:', error)
        allResults.value = []
      }
    }

    const filteredResults = computed(() => {
      if (!keyword.value?.trim()) return []

      // 创建模糊匹配模式，将关键词中的每个字符用.*分隔，实现...校...办...的效果
      const createFuzzyPattern = (str) => {
        // 直接在每个字符之间插入.*，不考虑特殊字符转义
        return str.split('').join('.*')
      }

      const pattern = createFuzzyPattern(keyword.value.trim())
      console.log("------------------------------pattern", pattern)
      const regex = new RegExp(pattern, 'i') // 不区分大小写匹配



      return allResults.value.filter(item =>
          (item.name && regex.test(item.name)) ||
          (item.room_code && regex.test(item.room_code)) ||
          (item.id && regex.test(item.id)) ||
          (item.floor && regex.test(item.floor)) ||
          (item.staff && regex.test(item.staff)) ||
          (item.remark && regex.test(item.remark)) ||
          (item.department && regex.test(item.department))
      )
    })

    watch(
        () => keyword.value,
        (newKeyword) => {
          if (newKeyword?.trim()) {
            fetchResults(newKeyword.trim())
            console.log(`正在搜索：${newKeyword.trim()}`)
          }
        },
        { immediate: true }
    )

    return {
      searchMode,
      keyword,
      filteredResults,
      selectedStartPoint,
      selectedEndPoint,
      startPoint,
      endPoint,
      locationIcon,
      startSearchStartPoint,
      startSearchEndPoint,
      selectPoint,
      cancelSearch,
      startNavigation
    }
  }
}
</script>

<style scoped>
.choose-point-page {
  width: 100vw;
  height: 100vh;
  background: white;
  display: flex;
  flex-direction: column;
  color: #333;
  overflow: hidden;
}

.header {
  padding: 30px 20px 20px;
  text-align: center;
}

.header h1 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.header p {
  font-size: 16px;
  opacity: 0.9;
}

.content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.location-info {
  background: #f0f0f0;
  border-radius: 16px;
  padding: 20px;
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.location-icon {
  width: 50px;
  height: 50px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.location-icon img {
  width: 30px;
  height: 30px;
}

.location-text h2 {
  font-size: 20px;
  margin-bottom: 5px;
  color: #666;
}

.location-text p {
  font-size: 16px;
  opacity: 0.9;
  color: #666;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.primary-button, .secondary-button {
  flex: 1;
  padding: 16px;
  border-radius: 12px;
  border: none;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #4285F4;
  color: white;
}

.primary-button:hover, .secondary-button:hover {
  background: #3367d6;
  transform: translateY(-2px);
}

.footer {
  padding: 20px;
}

.start-navigation {
  width: 100%;
  padding: 18px;
  border-radius: 12px;
  background: #4285F4;
  color: white;
  border: none;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.start-navigation:disabled {
  background: #a8c7fa;
  cursor: not-allowed;
}

.start-navigation:not(:disabled):hover {
  background: #3367d6;
  transform: translateY(-2px);
}

.search-mode {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%); /* Gradient background */
  color: #2d3748;
  transition: all 0.3s ease;
}

.search-header {
  padding: 20px 15px;
  display: flex;
  align-items: center;
  background: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Subtle shadow */
  border-bottom: none;
}

.search-header button {
  background: none;
  border: none;
  color: #3182ce; /* Softer blue */
  font-size: 16px;
  font-weight: 500;
  padding: 10px 15px;
  cursor: pointer;
  transition: color 0.2s ease;
}

.search-header button:hover {
  color: #2b6cb0; /* Darker blue on hover */
}

.search-header h2 {
  flex: 1;
  text-align: center;
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2d3748; /* Darker text */
  padding: 0 20px;
  transform: translateX(-25px);
}

.search-input {
  padding: 15px;
  background: #ffffff;
  margin: 10px 15px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* Subtle shadow for input area */
}

.search-box {
  width: 100%;
  padding: 14px;
  border: 1px solid #e2e8f0; /* Light border */
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.2s ease;
}

.search-box:focus {
  outline: none;
  border-color: #3182ce; /* Highlight on focus */
  box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.2); /* Focus ring */
}

.search-results {
  flex: 1;
  overflow-y: auto;
  padding: 10px 15px;
}

.result-item {
  padding: 15px;
  border-bottom: 1px solid #edf2f7; /* Lighter border */
  cursor: pointer;
  background: #ffffff;
  border-radius: 10px;
  margin-bottom: 10px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.result-item:hover {
  background: #f7fafc; /* Subtle hover background */
  transform: translateY(-2px); /* Lift effect */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* Shadow on hover */
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 6px;
  color: #2d3748; /* Darker text */
}

.result-details {
  display: flex;
  gap: 10px;
  font-size: 14px;
  color: #718096; /* Lighter gray for details */
}

.no-results {
  text-align: center;
  padding: 30px;
  color: #a0aec0; /* Light gray for no results */
  font-size: 16px;
  font-style: italic;
}

.selected-points {
  background: #f0f0f0;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 30px;
}

.point-display h3 {
  margin: 10px 0;
  font-size: 16px;
  color: #666;
}
</style>